package com.gylang.easy.lazy;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.gylang.easy.func.Ink;
import com.gylang.easy.util.MappingUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author gylang
 * data 2021/7/16
 */
public class Iter<T> {

	private Iterable<T> iterable;

	private Iter() {
	}

	public static <T> Iter<T> of(Iterable<T> iterable) {
		Iter<T> iter = new Iter<>();
		iter.iterable = iterable;
		return iter;
	}

	public void foreach(Consumer<T> consumer) {
		if (CollUtil.isNotEmpty(iterable)) {
			iterable.forEach(consumer);
		}
	}

	public <U> List<U> mapList(Function<T, U> mapper) {
		List<U> list = new ArrayList<>();
		if (CollUtil.isNotEmpty(iterable)) {
			for (T t : iterable) {
				list.add(mapper.apply(t));
			}
		}
		return list;
	}

	public <U> Iter<U> map(Function<T, U> mapper) {
		List<U> list = new ArrayList<>();
		if (CollUtil.isNotEmpty(iterable)) {
			for (T t : iterable) {
				list.add(mapper.apply(t));
			}
		}
		return Iter.of(list);
	}

	public <U> Iter<U> mapBeanElement(Class<U> clazz) {
		return map(m -> MappingUtil.map(m, clazz));
	}

	public <U> Iter<U> mapByConverter(Class<U> clazz) {
		return map(m -> Convert.convert(clazz, m));
	}

	public boolean empty() {
		return CollUtil.isEmpty(iterable);
	}

	public Iter<T> firstPresent(Consumer<T> consumer) {
		if (CollUtil.isNotEmpty(iterable)) {
			consumer.accept(CollUtil.getFirst(iterable));
		}
		return this;
	}

	public T getFirst() {
		if (CollUtil.isNotEmpty(iterable)) {
			return CollUtil.getFirst(iterable);
		}
		return null;
	}
	public T getFirstDefault(T def) {
		if (CollUtil.isNotEmpty(iterable)) {
			return CollUtil.getFirst(iterable);
		}
		return def;
	}

	public Iter<T> empty(Ink ink) {
		boolean empty = CollUtil.isEmpty(iterable);
		if (empty) {
			ink.invoke();
		}
		return this;
	}
}
